package com.laicunba.ext.web.controller.console.customer;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.json.simple.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.laicunba.ext.web.controller.BaseController;
import com.laicunba.util.ExcelUtil;
import com.laicunba.util.StringUtil;

/**
 * 外部用户相关处理类
 * 
 * @author lws
 *
 */
@Controller
@SuppressWarnings("unchecked")
@RequestMapping(value = "/console/ext/customer")
public class ExternalUserHandleController extends BaseController {
	
	@RequestMapping(value = "/external_user_share_form.htm")
	public ModelAndView form() {
		ModelAndView view = new ModelAndView();
		view.setViewName("external_user_share_form.jsp");
		view.addObject("defaultDir", System.getProperty("user.home"));
		return view;
	}

	@ResponseBody
	@RequestMapping(value = "/generate_user_share_script.htm")
	public String generateUserShareScript(HttpServletRequest request, @RequestParam("readFile") MultipartFile multipartFile) {
		JSONObject json = new JSONObject();
		if(multipartFile == null) {
			json.put("code", "failed");
			json.put("resMsg", "file is null");
			return json.toJSONString();
		}
		String packetName = StringUtil.isEmpty(request.getParameter("packetName")) ? "外部用户分享红包" : request.getParameter("packetName");
		String packetTotalAmount = StringUtil.isEmpty(request.getParameter("packetTotalAmount")) ? "0" : request.getParameter("packetTotalAmount");
		String splitCount = StringUtil.isEmpty(request.getParameter("splitCount")) ? "0" : request.getParameter("splitCount");
		String packetAmount = request.getParameter("packetAmount");
		if (StringUtil.isEmpty(packetAmount) || Double.parseDouble(packetAmount) <= 0) {
			json.put("code", "failed");
			json.put("resMsg", "生成失败，分割红包金额为空或<=0!");
			return json.toJSONString();
		}
		try {
			FileInputStream input = (FileInputStream) multipartFile.getInputStream();
			List<Map<String, String>> dataList = ExcelUtil.readXlsxExcelByStream(input);
			
			String fileName = multipartFile.getOriginalFilename();
			combineUserShareScript(dataList, fileName.substring(0, fileName.lastIndexOf('.')), packetName, packetTotalAmount, splitCount, packetAmount);
			json.put("code", "success");
			json.put("resMsg", "生成成功!");
		} catch (IOException e) {
			json.put("code", "failed");
			json.put("resMsg", "生成失败!");
			e.printStackTrace();
		} 
		
		return json.toJSONString();
	}
	// 组合用户分享红包及短信发送脚本
	private void combineUserShareScript(List<Map<String, String>> dataList, String fileName, String packetName, String packetTotalAmount, String splitCount, String packetAmount) {
		String sharedPacketId = StringUtil.genGUID();
		String sharedPacketSqlScript = "INSERT INTO lcb_shared_packet (\"name\", \"type\", \"amount\", \"summary\", \"conditions\", "
				    + "\"used_amount\", \"extract_type\", \"split_count\", \"used_count\", \"id\", \"owner_id\", \"gmt_create\", "
				    + "\"gmt_write\", \"create_uid\", \"write_uid\") "
				    + "VALUES ('" + packetName + "', 'CASH_COUPON', '" + packetTotalAmount + "', '', '[{\"type\":\"CPB\"}]', NULL, "
				    + "'AVG', '" + splitCount + "', '0', '" + sharedPacketId + "', 'root', now(), now(), 'root', 'root')";
		
		StringBuffer sbfSql = new StringBuffer(sharedPacketSqlScript);
		StringBuffer sbfSendMsg = new StringBuffer();
		sbfSql.append("\r\n\r\n");
		for (Map<String, String> dataMap : dataList) {
			String key = dataMap.keySet().iterator().next();
			String insertScript = "INSERT INTO lcb_shared_packet_item (\"mobile\", \"amount\", \"used\", \"packet_id\", \"uid\", "
					+ "\"id\", \"owner_id\", \"gmt_create\", \"gmt_write\", \"create_uid\", \"write_uid\") "
					+ "VALUES ('" + dataMap.get(key) + "', '" + packetAmount + "', 'f', '" + sharedPacketId + "', NULL, "
					+ "'" + StringUtil.genGUID() + "', NULL, now(), now(), NULL, NULL);";
			if (sbfSql.length() > 0) {
				sbfSql.append("\r\n");
			}
			sbfSql.append(insertScript);
			
			if (sbfSendMsg.length() > 0) {
				sbfSendMsg.append("\r\n");
			}
			
			sbfSendMsg.append("{\"mobile\":\"" + dataMap.get(key) + "\"}");
		}
		// 分享红包脚本
		RandomAccessFile rafSql = null;
		try {
			rafSql = new RandomAccessFile(System.getProperty("user.home") + "/" + fileName + ".sql", "rw");
			if(sbfSql.length() > 0) {
				rafSql.write(sbfSql.toString().getBytes());
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (rafSql != null) {
					rafSql.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		// 发送短信脚本
		RandomAccessFile rafSendMsg = null;
		try {
			rafSendMsg = new RandomAccessFile(System.getProperty("user.home") + "/" + fileName + ".txt", "rw");
			if(sbfSendMsg.length() > 0) {
				rafSendMsg.write(sbfSendMsg.toString().getBytes());
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (rafSendMsg != null) {
					rafSendMsg.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}
